<template>
  <div class="min-h-screen px-4 py-8 sm:px-6 lg:px-8 transition-colors duration-500" :class="isDarkMode ? 'bg-gray-900 text-gray-200' : 'bg-gray-50'">
    <div class="max-w-4xl mx-auto">
      <!-- 页面标题 -->
      <div class="mb-8 animate-fade-in-up" style="--delay: 200ms;">
        <button 
          @click="router.push('/home')" 
          class="mb-4 flex items-center transition-colors duration-300 transform hover:scale-105 active:scale-95 ease-spring"
          :class="isDarkMode ? 'text-purple-300 hover:text-purple-200' : 'text-purple-600 hover:text-purple-500'"
        >
          <font-awesome-icon icon="arrow-left" class="mr-2 transition-transform duration-300 hover:translate-x-[-3px]" />
          <span>返回主页</span>
        </button>
        <h1 class="text-2xl font-bold bg-gradient-to-r bg-clip-text animate-gradient-x"
            :class="isDarkMode ? 'from-purple-400 to-green-300 text-transparent' : 'from-purple-600 to-green-500 text-transparent'">
          设置
        </h1>
        <p class="mt-1" :class="isDarkMode ? 'text-gray-400' : 'text-gray-500'">自定义应用的外观和行为</p>
      </div>
      
      <!-- 主要内容 -->
      <div class="rounded-xl shadow-md overflow-hidden transition-all duration-500 transform hover:shadow-lg animate-fade-in-up hover-3d hover:scale-[1.01]"
           :class="isDarkMode ? 'bg-gray-800' : 'bg-white'"
           style="--delay: 300ms;">
        <!-- 外观设置 -->
        <div class="p-6 border-b transition-colors duration-500" :class="isDarkMode ? 'border-gray-700' : 'border-gray-200'">
          <h3 class="text-lg font-medium mb-4 bg-gradient-to-r bg-clip-text"
              :class="isDarkMode ? 'from-purple-400 to-green-300 text-transparent' : 'from-purple-600 to-green-500 text-transparent'">
            外观
          </h3>
          
          <!-- 主题设置 -->
          <div class="mb-6 animate-fade-in-up" style="--delay: 400ms;">
            <p class="text-sm font-medium mb-2" :class="isDarkMode ? 'text-gray-300' : 'text-gray-700'">主题</p>
            <div class="grid grid-cols-3 gap-3">
              <div 
                @click="changeTheme('light')"
                class="flex flex-col items-center p-3 rounded-lg cursor-pointer border transition-all duration-300 transform hover:scale-105 active:scale-95 ease-spring btn-ripple"
                :class="[
                  settings.theme === 'light' 
                    ? (isDarkMode ? 'bg-purple-900/30 border-purple-500' : 'bg-purple-50 border-purple-500') 
                    : (isDarkMode ? 'bg-gray-700 border-gray-600 hover:border-purple-400' : 'bg-white border-gray-200 hover:border-purple-200')
                ]"
              >
                <div class="w-full h-12 bg-white rounded-md shadow-sm mb-2"></div>
                <span class="text-sm font-medium" :class="isDarkMode ? 'text-gray-200' : 'text-gray-800'">浅色</span>
              </div>
              
              <div 
                @click="changeTheme('dark')"
                class="flex flex-col items-center p-3 rounded-lg cursor-pointer border transition-all duration-300 transform hover:scale-105 active:scale-95 ease-spring btn-ripple"
                :class="[
                  settings.theme === 'dark' 
                    ? (isDarkMode ? 'bg-purple-900/30 border-purple-500' : 'bg-purple-50 border-purple-500') 
                    : (isDarkMode ? 'bg-gray-700 border-gray-600 hover:border-purple-400' : 'bg-white border-gray-200 hover:border-purple-200')
                ]"
              >
                <div class="w-full h-12 bg-gray-800 rounded-md shadow-sm mb-2"></div>
                <span class="text-sm font-medium" :class="isDarkMode ? 'text-gray-200' : 'text-gray-800'">深色</span>
              </div>
              
              <div 
                @click="changeTheme('system')"
                class="flex flex-col items-center p-3 rounded-lg cursor-pointer border transition-all duration-300 transform hover:scale-105 active:scale-95 ease-spring btn-ripple"
                :class="[
                  settings.theme === 'system' 
                    ? (isDarkMode ? 'bg-purple-900/30 border-purple-500' : 'bg-purple-50 border-purple-500') 
                    : (isDarkMode ? 'bg-gray-700 border-gray-600 hover:border-purple-400' : 'bg-white border-gray-200 hover:border-purple-200')
                ]"
              >
                <div class="w-full h-12 bg-gradient-to-r from-white to-gray-800 rounded-md shadow-sm mb-2"></div>
                <span class="text-sm font-medium" :class="isDarkMode ? 'text-gray-200' : 'text-gray-800'">跟随系统</span>
              </div>
            </div>
          </div>
          
          <!-- 字体系列 -->
          <div class="mb-6 animate-fade-in-up" style="--delay: 500ms;">
            <p class="text-sm font-medium mb-2" :class="isDarkMode ? 'text-gray-300' : 'text-gray-700'">字体系列</p>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
              <div 
                v-for="font in availableFonts" 
                :key="font.value"
                @click="settings.fontFamily = font.value"
                class="flex items-center p-3 rounded-lg cursor-pointer border transition-all duration-300 transform hover:scale-[1.02] ease-spring"
                :class="[
                  settings.fontFamily === font.value 
                    ? (isDarkMode ? 'bg-purple-900/30 border-purple-500' : 'bg-purple-50 border-purple-500') 
                    : (isDarkMode ? 'bg-gray-700 border-gray-600 hover:border-purple-400' : 'bg-white border-gray-200 hover:border-purple-200')
                ]"
              >
                <div class="flex-1">
                  <span class="text-base" 
                        :class="isDarkMode ? 'text-gray-200' : 'text-gray-800'" 
                        :style="{ fontFamily: font.value }">
                    {{ font.label }}
                  </span>
                  <p class="text-xs mt-1" :class="isDarkMode ? 'text-gray-400' : 'text-gray-500'">
                    {{ font.description }}
                  </p>
                </div>
                <div v-if="settings.fontFamily === font.value" 
                     class="w-5 h-5 rounded-full bg-gradient-to-r from-purple-500 to-green-400 flex items-center justify-center">
                  <font-awesome-icon icon="check" class="text-white text-xs" />
                </div>
              </div>
            </div>
          </div>
          
          <!-- 字体大小 -->
          <div class="mb-6 animate-fade-in-up" style="--delay: 600ms;">
            <div class="flex items-center justify-between mb-2">
              <p class="text-sm font-medium" :class="isDarkMode ? 'text-gray-300' : 'text-gray-700'">字体大小</p>
              <span class="text-sm" :class="isDarkMode ? 'text-gray-400' : 'text-gray-500'">{{ settings.fontSize }}px</span>
            </div>
            <input 
              type="range" 
              min="12" 
              max="20" 
              step="1" 
              v-model="settings.fontSize"
              class="w-full h-2 rounded-lg appearance-none cursor-pointer slider-thumb"
              :class="isDarkMode ? 'bg-gray-600' : 'bg-gray-200'"
            />
            <div class="flex justify-between text-xs mt-1" :class="isDarkMode ? 'text-gray-400' : 'text-gray-500'">
              <span>幼儿园</span>
              <span>成年人</span>
              <span>老年人</span>
            </div>
            
            <!-- 字体预览 -->
            <div class="mt-4 p-3 rounded-lg border transition-all duration-300 transform hover:scale-[1.01]"
                 :class="isDarkMode ? 'border-gray-700 bg-gray-700/50' : 'border-gray-200 bg-gray-50'"
                 :style="{ 
                   fontSize: `${settings.fontSize}px`, 
                   fontFamily: settings.fontFamily 
                 }">
              <p class="mb-2" :class="isDarkMode ? 'text-gray-200' : 'text-gray-800'">字体预览</p>
              <p class="text-sm" :class="isDarkMode ? 'text-gray-300' : 'text-gray-600'">
                这是一段示例文本，用于预览当前所选字体的外观。
              </p>
              <p class="text-sm mt-2" :class="isDarkMode ? 'text-gray-300' : 'text-gray-600'">
                The quick brown fox jumps over the lazy dog.
              </p>
            </div>
          </div>
        </div>
        
        <!-- 聊天设置 -->
        <div class="p-6 border-b transition-colors duration-500 animate-fade-in-up" 
             :class="isDarkMode ? 'border-gray-700' : 'border-gray-200'"
             style="--delay: 700ms;">
          <h3 class="text-lg font-medium mb-4 bg-gradient-to-r bg-clip-text"
              :class="isDarkMode ? 'from-purple-400 to-green-300 text-transparent' : 'from-purple-600 to-green-500 text-transparent'">
            聊天
          </h3>
          
          <div class="space-y-4">
            <!-- 自动回复 -->
            <div class="flex items-center justify-between p-3 rounded-lg transition-all duration-300 hover:scale-[1.02]"
                 :class="isDarkMode ? 'hover:bg-gray-700/60' : 'hover:bg-gray-50/80'">
              <div>
                <p class="text-sm font-medium" :class="isDarkMode ? 'text-gray-200' : 'text-gray-800'">AI智能续写</p>
                <p class="text-xs" :class="isDarkMode ? 'text-gray-400' : 'text-gray-500'">允许AI预测并自动续写您的消息</p>
              </div>
              <div class="relative inline-block w-12 mr-2 align-middle">
                <input 
                  type="checkbox" 
                  id="autoComplete" 
                  v-model="settings.autoComplete" 
                  class="toggle-checkbox absolute block w-5 h-5 rounded-full bg-white border-4 appearance-none cursor-pointer"
                  :class="{ 'translate-x-full border-purple-500': settings.autoComplete, 'border-gray-300': !isDarkMode && !settings.autoComplete, 'border-gray-600': isDarkMode && !settings.autoComplete }"
                />
                <label 
                  for="autoComplete" 
                  class="toggle-label block overflow-hidden h-5 rounded-full cursor-pointer transition-colors duration-300 ease-spring"
                  :class="{ 
                    'bg-gradient-to-r from-purple-500 to-green-400': settings.autoComplete, 
                    'bg-gray-300': !settings.autoComplete && !isDarkMode,
                    'bg-gray-600': !settings.autoComplete && isDarkMode
                  }"
                ></label>
              </div>
            </div>
            
            <!-- 保存历史 -->
            <div class="flex items-center justify-between p-3 rounded-lg transition-all duration-300 hover:scale-[1.02]"
                 :class="isDarkMode ? 'hover:bg-gray-700/60' : 'hover:bg-gray-50/80'">
              <div>
                <p class="text-sm font-medium" :class="isDarkMode ? 'text-gray-200' : 'text-gray-800'">保存聊天历史</p>
                <p class="text-xs" :class="isDarkMode ? 'text-gray-400' : 'text-gray-500'">退出后仍保留聊天记录</p>
              </div>
              <div class="relative inline-block w-12 mr-2 align-middle">
                <input 
                  type="checkbox" 
                  id="saveHistory" 
                  v-model="settings.saveHistory" 
                  class="toggle-checkbox absolute block w-5 h-5 rounded-full bg-white border-4 appearance-none cursor-pointer"
                  :class="{ 'translate-x-full border-purple-500': settings.saveHistory, 'border-gray-300': !isDarkMode && !settings.saveHistory, 'border-gray-600': isDarkMode && !settings.saveHistory }"
                />
                <label 
                  for="saveHistory" 
                  class="toggle-label block overflow-hidden h-5 rounded-full cursor-pointer transition-colors duration-300 ease-spring"
                  :class="{ 
                    'bg-gradient-to-r from-purple-500 to-green-400': settings.saveHistory, 
                    'bg-gray-300': !settings.saveHistory && !isDarkMode,
                    'bg-gray-600': !settings.saveHistory && isDarkMode
                  }"
                ></label>
              </div>
            </div>
            
            
           
          </div>
        </div>
        
     
        <!-- 按钮 -->
        <div class="p-6 flex justify-end space-x-3 animate-fade-in-up" style="--delay: 900ms;">
          <button 
            @click="resetSettings" 
            class="px-4 py-2 rounded-md transition-all duration-300 transform hover:scale-105 active:scale-95 ease-spring btn-ripple"
            :class="isDarkMode ? 'bg-gray-700 text-gray-300 hover:bg-gray-600' : 'bg-gray-100 text-gray-700 hover:bg-gray-200'"
          >
            重置为默认
          </button>
          <button 
            @click="saveSettings" 
            class="px-4 py-2 rounded-md text-white transition-all duration-300 transform hover:scale-105 active:scale-95 ease-spring bg-gradient-to-r btn-ripple shadow-sm"
            :class="isDarkMode 
              ? 'from-purple-600 to-green-500 hover:from-purple-700 hover:to-green-600' 
              : 'from-purple-500 to-green-400 hover:from-purple-600 hover:to-green-500'"
          >
            保存设置
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, computed } from 'vue';
import { useRouter } from 'vue-router';
import { toast } from '../services/toastService';

const router = useRouter();

// 深色模式状态
const isDarkMode = ref(false);

// 从localStorage加载主题偏好
const loadThemePreference = () => {
  const savedPreference = localStorage.getItem('darkModePreference');
  if (savedPreference !== null) {
    isDarkMode.value = savedPreference === 'true';
  } else {
    // 如果没有保存的偏好，尝试使用系统偏好
    const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
    isDarkMode.value = prefersDark;
  }
};

// 保存主题偏好到本地存储
const saveThemePreference = (value) => {
  localStorage.setItem('darkModePreference', value.toString());
  // 实时应用深色模式状态
  isDarkMode.value = value;
};

// 可用的字体选项
const availableFonts = [
  { 
    value: "'Noto Sans SC', sans-serif", 
    label: "思源黑体", 
    description: "现代无衬线字体，适合长时间阅读"
  },
  { 
    value: "'PingFang SC', 'Microsoft YaHei', sans-serif", 
    label: "苹方/微软雅黑", 
    description: "系统默认字体，清晰易读"
  },
  { 
    value: "'Song', 'SimSun', serif", 
    label: "宋体", 
    description: "传统衬线字体，正式场合常用"
  },
  { 
    value: "'Noto Serif SC', serif", 
    label: "思源宋体", 
    description: "现代衬线字体，优雅大方"
  }
];

// 用户设置
const defaultSettings = {
  theme: 'light',
  fontSize: 16,
  fontFamily: "'PingFang SC', 'Microsoft YaHei', sans-serif",
  autoComplete: true,
  saveHistory: true,
  chatSounds: false,
  language: 'zh-CN'
};

// 初始化设置，尝试从localStorage获取
const loadSettings = () => {
  try {
    const savedSettings = localStorage.getItem('appSettings');
    if (savedSettings) {
      return { ...defaultSettings, ...JSON.parse(savedSettings) };
    }
  } catch (error) {
    console.error('加载设置失败:', error);
  }
  return { ...defaultSettings };
};

const settings = ref(loadSettings());

// 组件挂载时确保主题与存储中的darkModePreference同步
onMounted(() => {
  // 首先加载主题偏好
  loadThemePreference();
  
  // 然后根据主题偏好设置settings.theme
  if (isDarkMode.value) {
    settings.value.theme = 'dark';
  } else {
    settings.value.theme = 'light';
  }
  
  // 监听系统主题变化
  setupSystemThemeListener();
  // 应用字体设置
  applyFontToDocument();
});

// 应用字体到document
const applyFontToDocument = () => {
  document.documentElement.style.setProperty('--app-font-family', settings.value.fontFamily);
  document.documentElement.style.setProperty('--app-font-size', `${settings.value.fontSize}px`);
};

// 修改主题并同步全局深色模式状态
const changeTheme = (theme) => {
  settings.value.theme = theme;
  
  // 根据主题设置更新深色模式状态
  if (theme === 'light') {
    saveThemePreference(false);
  } else if (theme === 'dark') {
    saveThemePreference(true);
  } else if (theme === 'system') {
    // 如果是跟随系统，则使用系统偏好
    const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
    saveThemePreference(prefersDark);
  }
  
  // 立即保存设置以确保整个应用都能更新
  saveSettings(false); // 不显示成功消息
  
  toast.info(`主题已切换为${theme === 'light' ? '浅色' : theme === 'dark' ? '深色' : '跟随系统'}`, 2000);
};

// 监听系统主题变化
const setupSystemThemeListener = () => {
  const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
  
  const handleChange = (e) => {
    if (settings.value.theme === 'system') {
      saveThemePreference(e.matches);
    }
  };
  
  // 添加监听器
  if (mediaQuery.addEventListener) {
    mediaQuery.addEventListener('change', handleChange);
  } else if (mediaQuery.addListener) {
    // 兼容旧版API
    mediaQuery.addListener(handleChange);
  }
};

// 重置设置
const resetSettings = () => {
  settings.value = { ...defaultSettings };
  
  // 同步深色模式状态
  if (settings.value.theme === 'light') {
    saveThemePreference(false);
  } else if (settings.value.theme === 'dark') {
    saveThemePreference(true);
  } else {
    const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
    saveThemePreference(prefersDark);
  }
  
  // 应用字体设置
  applyFontToDocument();
  
  toast.info('设置已重置为默认值', 2000);
};

// 保存设置
const saveSettings = (showToast = true) => {
  try {
    localStorage.setItem('appSettings', JSON.stringify(settings.value));
    
    // 确保深色模式状态与主题设置同步
    if (settings.value.theme === 'light') {
      saveThemePreference(false);
    } else if (settings.value.theme === 'dark') {
      saveThemePreference(true);
    } else if (settings.value.theme === 'system') {
      const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
      saveThemePreference(prefersDark);
    }
    
    // 应用字体设置
    applyFontToDocument();
    
    if (showToast) {
      toast.success('设置已保存', 2000);
    }
  } catch (error) {
    console.error('保存设置失败:', error);
    if (showToast) {
      toast.error('保存设置失败，请重试', 2000);
    }
  }
};

// 监听字体设置变化
watch(() => [settings.value.fontSize, settings.value.fontFamily], () => {
  applyFontToDocument();
}, { deep: true });

// 监听深色模式变化，确保与主题设置同步
watch(() => isDarkMode.value, (newValue) => {
  // 如果主题不是跟随系统，则根据深色模式状态更新主题
  if (settings.value.theme !== 'system') {
    settings.value.theme = newValue ? 'dark' : 'light';
  }
});
</script>

<style scoped>
/* 切换开关样式 */
.toggle-checkbox {
  left: 0;
  transition: transform 0.3s ease-in-out, border-color 0.3s ease-in-out;
  z-index: 1;
}
.toggle-checkbox.translate-x-full {
  transform: translateX(100%);
}
.toggle-label {
  width: 100%;
  position: relative;
  overflow: hidden;
}
.toggle-label::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 200%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  transition: all 0.5s ease-in-out;
}
.toggle-label:hover::before {
  left: 100%;
}

/* 自定义滑块样式 */
.slider-thumb {
  -webkit-appearance: none;
  appearance: none;
}
.slider-thumb::-webkit-slider-thumb {
  -webkit-appearance: none;
  appearance: none;
  width: 18px;
  height: 18px;
  border-radius: 50%;
  cursor: pointer;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  background: linear-gradient(to right, #8153ff, #93dc24);
  transition: all 0.3s ease;
}
.slider-thumb::-webkit-slider-thumb:hover {
  transform: scale(1.1);
  box-shadow: 0 2px 8px rgba(129, 83, 255, 0.4);
}
.slider-thumb::-moz-range-thumb {
  width: 18px;
  height: 18px;
  border: none;
  border-radius: 50%;
  cursor: pointer;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  background: linear-gradient(to right, #8153ff, #93dc24);
  transition: all 0.3s ease;
}
.slider-thumb::-moz-range-thumb:hover {
  transform: scale(1.1);
  box-shadow: 0 2px 8px rgba(129, 83, 255, 0.4);
}

/* 渐变动画 */
.animate-gradient-x {
  background-size: 200% 200%;
  animation: gradient-x 8s ease infinite;
}

@keyframes gradient-x {
  0% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0% 50%;
  }
}

/* 弹性缓动 */
.ease-spring {
  transition-timing-function: cubic-bezier(0.34, 1.56, 0.64, 1);
}

/* 淡入上升动画 */
.animate-fade-in-up {
  opacity: 0;
  transform: translateY(15px);
  animation: fade-in-up 0.7s cubic-bezier(0.34, 1.56, 0.64, 1) forwards;
  animation-delay: var(--delay, 0ms);
}

@keyframes fade-in-up {
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 3D悬浮效果 */
.hover-3d {
  transition: all 0.5s cubic-bezier(0.34, 1.56, 0.64, 1);
  transform-style: preserve-3d;
  perspective: 1000px;
}

.hover-3d:hover {
  transform: rotateX(2deg) rotateY(2deg) scale(1.02);
  box-shadow: 0 15px 30px rgba(0, 0, 0, 0.1);
}

/* 按钮点击波纹效果 */
.btn-ripple {
  position: relative;
  overflow: hidden;
}

.btn-ripple::after {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  width: 5px;
  height: 5px;
  background: rgba(255, 255, 255, 0.5);
  opacity: 0;
  border-radius: 100%;
  transform: scale(1) translate(-50%, -50%);
  transform-origin: 50% 50%;
}

.btn-ripple:active::after {
  animation: ripple 0.6s ease-out;
}

@keyframes ripple {
  0% {
    transform: scale(0) translate(-50%, -50%);
    opacity: 0.5;
  }
  100% {
    transform: scale(20) translate(-50%, -50%);
    opacity: 0;
  }
}

/* 自定义滚动条 */
::-webkit-scrollbar {
  width: 5px;
  height: 5px;
}

::-webkit-scrollbar-track {
  background: transparent;
  border-radius: 3px;
}

::-webkit-scrollbar-thumb {
  background: linear-gradient(to bottom, #8153ff, #93dc24);
  border-radius: 9999px;
  transition: all 0.5s cubic-bezier(0.34, 1.56, 0.64, 1);
}

::-webkit-scrollbar-thumb:hover {
  background: linear-gradient(to bottom, #9673ff, #a3ec34);
}

/* 输入框焦点特效 */
input:focus, select:focus {
  box-shadow: 0 0 0 2px rgba(129, 83, 255, 0.2);
  animation: input-pulse 2s infinite;
}

@keyframes input-pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(129, 83, 255, 0.4);
  }
  70% {
    box-shadow: 0 0 0 6px rgba(129, 83, 255, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(129, 83, 255, 0);
  }
}
</style> 